package org.leon.dubbo.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Activate(group = {CommonConstants.CONSUMER, CommonConstants.PROVIDER})
public class TransportIPFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        final String hostKey = "customer.host";
        try {
            String customerHost = invocation.getAttachment(hostKey);
            if (customerHost == null){
                ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = servletRequestAttributes.getRequest();
                String ip = request.getRemoteAddr();
                invocation.getAttachments().put(hostKey, ip);
            } else {
                System.out.println("customer host address is " + customerHost);
            }
        } catch (Exception ue) {
            ue.printStackTrace();
        }
        return invoker.invoke(invocation);
    }
}
